import React, { useEffect, useMemo, useState } from "react";
import axios from "axios";
import { Table, Button, Tag, notification } from "antd";
import { useHistory, useParams } from "react-router-dom";
import { readToken } from "../../../util";

/** @import {News, NewsCategoryRoleDTO, ReactState} from "../../../types"; */

export default function AuditList() {
    const history = useHistory();
    /** @type {ReactState<News[]>} */
    const [drafts, setDrafts] = useState([]);

    const auditStates = ["未审核", "审核中", "已通过", "未通过"];
    const auditColors = ["black", "orange", "green", "red"];
    const columns = [
        {
            title: "新闻标题",
            render: (news) => <a href={"#/news-manage/preview/" + news.id}>{news.title}</a>
        },
        {
            title: "作者",
            dataIndex: "author"
        },
        {
            title: "新闻分类",
            dataIndex: "category",
            render: (c) => c.title
        },
        {
            title: "审核状态",
            dataIndex: "auditState",
            render: (as) => <Tag color={auditColors[as]}>{auditStates[as]}</Tag>
        },
        {
            title: "操作",
            dataIndex: "auditState",
            /** @type {(as: number, news: News)} */
            render: (as, news) => (
                <div>
                    {as === 1 && <Button type="primary" onClick={() => handleRevert(news)}>撤销</Button>}
                    {as === 2 && <Button type="primary" onClick={() => handlePublish(news)}>发布</Button>}
                    {as === 3 && <Button type="primary" onClick={() => handleEdit(news)}>修改</Button>}
                </div>
            )
        }
    ];

    // 拉取数据
    const fetchData = () => {
        const {username} = readToken();
        axios.get("/news?_embed=category&auditState_ne=0&publishState_lte=1&author=" + username)
            .then((res) => setDrafts(res.data));
    };
    useEffect(fetchData, []);

    /** 撤销新闻 @type {(news: News) => void} */
    const handleRevert = (news) => {
        axios.patch("/news/" + news.id, {
            auditState: 0
        })
        .then(() => {
            notification.success({
                message: "操作成功",
                description: "已撤销该新闻的审核，可以在草稿箱中查看该文章。"
            });
            fetchData();
        });
    };

    /** 发布新闻 @type {(news: News) => void} */
    const handlePublish = (news) => {
        axios.patch("/news/" + news.id, {
            publishState: 2
        })
        .then(() => {
            notification.success({
                message: "操作成功",
                description: "已发布该新闻，可以在已发布中查看该文章。"
            });
            fetchData();
        });

    };

    /** 修改新闻 @type {(news: News) => void} */
    const handleEdit = (news) => {
        history.push("/news-manage/update/" + news.id);
    };

    return (
        <div>
            <Table dataSource={drafts} columns={columns} rowKey={(item) => item.id }/>
        </div>
    );
}
